package com.xb.xbpm.service.impl;

import com.xb.xbpm.bean.Site;
import com.xb.xbpm.bean.User;
import com.xb.xbpm.bean.UserRole;
import com.xb.xbpm.mapper.SiteMapper;
import com.xb.xbpm.mapper.UserMapper;
import com.xb.xbpm.mapper.UserRoleMapper;
import com.xb.xbpm.service.ILoginService;
import com.xb.xbpm.utils.Constants;
import com.xb.xbpm.utils.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Author gxd
 * @Date： 2018/7/25
 */
@Service
public class LoginService implements ILoginService {
    @Autowired
    private UserMapper userMapper;//这里会报错，但是并不会影响
    @Autowired
    private UserRoleMapper userRoleMapper;


    @Transactional
    @Override
    public Integer saveUser(User user) throws Exception {
        //判断用户名是否存在
        List<User> list=new ArrayList<User>();
        Map<String, String> map = new HashMap<String, String>();
        map.put("username",user.getUsername());
        list=userMapper.getUserByParam(map);
        if(list.size()>0){
            return 2;//用户名存在
        }
        String userid=getlmId();
        user.setId(userid);
        user.setPassword(Tools.md5(user.getPassword()));
        Integer r=userMapper.insertSelective(user);
        //保存角色
        UserRole ur=new UserRole();
        ur.setId(Tools.getUUID());
        ur.setUid(userid);
        ur.setRole(Constants.DefaultRole);
        userRoleMapper.insert(ur);

        return r;
    }

    private  String getlmId(){
        String year=Tools.date2Str(new Date(),"yyyyMMdd");
        year=year.substring(2,4);
        return  year+UUID.randomUUID().toString().replace("-", "").substring(0, 8);
    }

    @Override
    public User getUserInfo(User user) {
        List<User> list=new ArrayList<User>();
        Map<String, String> map = new HashMap<String, String>();
        map.put("username",user.getUsername());

        if(Tools.notEmpty(user.getPassword())){
            String password=Tools.md5(user.getPassword());
            map.put("password",password);
        }

        list=userMapper.getUserByParam(map);
        if(list.size()>0){
            User u=list.get(0);
            //查询角色
            List<String> roles=userMapper.getUserRole(u.getId());
            u.setRole(roles);
            return u;
        }
        return null;
    }
}
